﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class UserViewmodel : ViewmodelBase
    {
        #region Constructor
        public UserViewmodel()
        {
            UserClient.GetAllUserItemsCompleted += GetAllUserItemsCompleted;
            UserClient.UpdateUserStatusCompleted += UpdateUserStatusCompleted;
            UserClient.GetUserInfoCompleted += GetUserInfoCompleted;
            UserClient.ChangeUserLevelCompleted += ChangeUserLevelCompleted;
            CommonBaseClient.GetUserLevelAllItemsCompleted += GetUserLevelAllItemsCompleted;
            if (DataContext.IsValid)
            {
                LoadData();
                LoadRelatedData();
            }
        }

        #endregion

        #region Methods
        private void GetUserLevelAllItemsCompleted(object sender, DataService.GetUserLevelAllItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    UserLevelCollection = new ObservableCollection<UserLevelInfo>(e.Result.Entities.OfType<UserLevelInfo>());
                }
            }
        }

        private void ChangeUserLevelCompleted(object sender, DataService.ChangeUserLevelCompletedEventArgs e)
        {
            Operation = EntityOperation.None;
            SelectedUserLevel = null;
            UpdateEntity = new UserInfo();

            LoadData();
        }

        private void GetUserInfoCompleted(object sender, DataService.GetUserInfoCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                if(e.Result.Result == ResultValue.Succeed)
                {
                    Operation = EntityOperation.Update;
                    UpdateEntity = e.Result.Entities.OfType<UserInfo>().FirstOrDefault();
                    if (UpdateEntity.UserLevelId > 0)
                    {
                        SelectedUserLevel = UserLevelCollection.FirstOrDefault(t => t.Id == UpdateEntity.UserLevelId);
                    }
                }
            }
        }

        private void UpdateUserStatusCompleted(object sender, DataService.UpdateUserStatusCompletedEventArgs e)
        {
            LoadData();
        }

        private void GetAllUserItemsCompleted(object sender, DataService.GetAllUserItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects.AsEnumerable()
                                 select new
                                 {
                                     Id = t["Id"],
                                     Name = t["Name"],
                                     Account = t["Account"],
                                     RegisterTime = (DateTime)t["RegisterTime"],
                                     Kind = t["UserKind"],
                                     Industry = t["Industry"],
                                     AccountStatus = (AccountStatusValue)Convert.ToInt32(t["AccountStatus"]),
                                     UserLevel = string.IsNullOrEmpty(t["UserLevel"].ToString()) ? "未设置" : t["UserLevel"]
                                 });
                    ItemsCollection = new ObservableCollection<object>(items);
                    ItemsCount = e.Result.TotalCount;
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            UserClient.GetAllUserItemsAsync(Account, Password, Keywords, Index, 20);
        }

        private void LoadRelatedData()
        {
            if (UserLevelCollection.IsNullOrEmpty())
            {
                CommonBaseClient.GetUserLevelAllItemsAsync(Account, Password);
            }
        }
        #endregion

        #region Collection
        private ObservableCollection<UserLevelInfo> _userLevelCollection;
        public ObservableCollection<UserLevelInfo> UserLevelCollection
        {
            get { return _userLevelCollection; }
            set
            {
                _userLevelCollection = value;
                RaisePropertyChanged(() => UserLevelCollection);
                RaisePropertyChanged(() => ChangeCommand);
            }
        }

        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }
        #endregion

        #region Pagination

        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
            }
        }
        #endregion

        #region Properties
        private UserInfo _updateEntity = new UserInfo();
        public UserInfo UpdateEntity
        {
            get { return _updateEntity; }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
            }
        }

        private UserLevelInfo _selectedUserLevel;
        public UserLevelInfo SelectedUserLevel
        {
            get { return _selectedUserLevel; }
            set
            {
                _selectedUserLevel = value;
                RaisePropertyChanged(() => SelectedUserLevel);
                if (SelectedUserLevel != null && UpdateEntity != null)
                {
                    UpdateEntity.UserLevelId = SelectedUserLevel.Id;
                }
            }
        }

        #endregion

        #region Commands
        public ICommand BlockCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    UserClient.UpdateUserStatusAsync(Account, Password, id, AccountStatusValue.Block);

                });
            }
        }

        public ICommand UnblockCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    UserClient.UpdateUserStatusAsync(Account, Password, id, AccountStatusValue.Normal);
                });
            }
        }

        public ICommand ChangeCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    LoadRelatedData();
                    UserClient.GetUserInfoAsync(Account, Password, id);
                }, t => UserLevelCollection != null && UserLevelCollection.Count > 0);
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    UserClient.UpdateUserStatusAsync(Account, Password, id, AccountStatusValue.Removed);
                });
            }
        }

        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Index = 1;
                        ItemsCount = 0;
                        LoadData();
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Operation = EntityOperation.None;
                        SelectedUserLevel = null;
                        UpdateEntity = new UserInfo();
                    }
                };
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        UserClient.ChangeUserLevelAsync(Account, Password, UpdateEntity.Id, UpdateEntity.UserLevelId);
                    }
                };
            }
        }
        #endregion
    }
}
